import argparse
import sys
import os
import time
from deepsignal3.utils.process_utils import get_motif_seqs

neg_num = 0  # Replacing mp.Value since we're now single-threaded

def read_and_process_feature(input_file, output_file, standard, batch_size=1):
    print('Begin processing', flush=True)
    fea_list = []
    motif_seqs = get_motif_seqs('CG', True)

    with open(input_file, 'r') as f, open(output_file, 'w') as wf:
        for line in f:
            words = line.strip().split('\t')
            bisulfite = [float(x) for x in words[15].split(",")]
            pred_pos = [int(x) for x in words[5].split(",")]
            ref_pos = [int(x) for x in words[16].split(",")]
            density_results = words[-5:]
            density = [list(map(float, row.split(','))) for row in density_results]

            smaller_than_10 = [index for index, value in enumerate(bisulfite) if value <= 10]
            bisulfite = [-1  for x in bisulfite]
            change = 0
            change_index=[]
            for index in smaller_than_10:
                flag = 0
                for s in range(len(standard)):
                    if density[s][index] != -1 and density[s][index] <= standard[s]:
                        flag += 1
                if flag >= 5:
                    bisulfite[index] = 0
                    change += 1
                    change_index.append(index)
            
            if change == 0:
                continue
            pred_pos_new = [pred_pos[i] for i in change_index]
            ref_pos_new = [ref_pos[i] for i in change_index]
            pred_pos_text = ','.join(
                        [str(x) for x in pred_pos_new])
            ref_pos_text = ','.join(
                        [str(x) for x in ref_pos_new])
            
            global neg_num
            
            neg = [index for index, value in enumerate(bisulfite) if value == 0]
            neg_num += len(neg)

            bisulfite_text = ','.join([str(bisulfite[x]) for x in range(len(bisulfite)) if bisulfite[x] != -1])
            fea_str = '\t'.join(words[:5]+[pred_pos_text] +words[6:15]+ [bisulfite_text] + [ref_pos_text])
            fea_list.append(fea_str)

            if len(fea_list) >= batch_size:
                for one_features_str in fea_list:
                    wf.write(one_features_str + "\n")
                wf.flush()
                fea_list = []

        if len(fea_list) > 0:
            for one_features_str in fea_list:
                wf.write(one_features_str + "\n")
            wf.flush()

    print('Processing completed. Added negative number is: {}'.format(neg_num), flush=True)

def parse_args():
    parser = argparse.ArgumentParser("")
    parser.add_argument("--input", type=str, required=True)
    parser.add_argument("--output", type=str, required=True)
    return parser.parse_args()

def main():
    args = parse_args()
    standard = [0.0477, 0.0489, 0.0329, 0.0248, 0.0298]
    read_and_process_feature(args.input, args.output, standard)

if __name__ == '__main__':
    sys.exit(main())
